[% setvar title Overloadable && and || %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Overloadable &amp;&amp; and ||</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Jean-Louis Leroy
  Date: 4 Aug 2000
  Mailing List: <a href='mailto:perl6-language@perl.org'>perl6-language@perl.org</a>
  Number: 20
  Version: 1
  Status: Developing</pre>
<a name='ABSTRACT'></a><h1>ABSTRACT</h1>
<p>It should be possible to overload &amp;&amp; and ||, for this has very
legitimate uses.</p>
<a name='DISCUSSION'></a><h1>DISCUSSION</h1>
<p>The reason often cited for not allowing the overloading of logical
junctions (i.e. &amp;&amp; and ||, LJ for short) is that LJs are
'short-circuiting' operators, iow the second argument is not always
evaluated. User-defined LJs cannot benefit from this feature, and
making it possible to overload LJs would only result in confusion.</p>
<p>There are two arguments to the contrary.</p>
<p>Even without the conditional evaluation feature, there are
very legitimate uses for overloaded LJs. The arguments are not always
Perl expressions - they may be objects that participate in - for
example - abstract syntax trees.</p>
<p>An example of this can be found in Tangram, a persistence
facility. The following Perl code:</p>
<pre>	my $p = $storage-&gt;remote('NaturalPerson');

	@results = $storage-&gt;select($p,
		$p-&gt;{age} &gt; 10 &amp; $p-&gt;{age} &lt; 20);</pre>
<p>...gets translated to the following SQL code:</p>
<pre>	SELECT t1.id, t1.classId, t1.country, t1.address,
		t2.age, t2.partner, t2.first_name, t2.name
	FROM Person t1, NaturalPerson t2
	WHERE (t2.age &gt; 10 AND t2.age &lt; 20) AND t2.id = t1.id</pre>
<p>Note that the 'short-circuiting' behavior does occur, in a way: on the
database side. Also note that '&amp;' has to be used instead of '&amp;&amp;',
because the latter is not overloadable. Using the more intuitive '&amp;&amp;'
silently results in incorrect code.</p>
<p>The second argument why overloadable LJs should be supported is that
it seems possible to make them enjoy the conditional evaluation of the
built-in LJs. When the compiler sees code like:</p>
<pre>	expr1 &amp;&amp; expr2</pre>
<p>...and detects that the LJ is overloaded, it could replace it with:</p>
<pre>	user_defined_and( sub { $expr1 }, sub { $expr2 } )</pre>
<p>The user-defined '&amp;&amp;' can thus decide whether or not to evaluate its
operands, for example:</p>
<pre>	sub user_defined_and
	{
		# mimic built-in operator &amp;&amp;
		my ($left, $right) = @_;
		
		if (my $result = $left-&gt;())
		{
			return $result;
		}

		return $right-&gt;();
	}</pre>
</div>
